package com.sx.micowell.module.smartDevice;

import android.annotation.SuppressLint;
import android.os.CountDownTimer;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.widget.Chronometer;

import androidx.annotation.Nullable;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.example.mvvm.bar.TitleBar;
import com.example.mvvm.base.ContainerActivity;
import com.example.mvvm.base.action.TitleBarAction;
import com.example.mvvm.base.data.DataBindingConfig;
import com.example.mvvm.until.LogUtils;
import com.gyf.immersionbar.ImmersionBar;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.miloyu.modelnet.network.ApiResponse;
import com.miloyu.modelnet.network.HttpClient;
import com.miloyu.modelnet.network.tools.RxUtils;
import com.sx.micowell.R;
import com.sx.micowell.databinding.FragDeviceDataBinding;
import com.sx.micowell.framework.app.IntentKey;
import com.sx.micowell.framework.app.MyFragment;
import com.sx.micowell.framework.arouth.RoutePath;
import com.sx.micowell.framework.tools.DateUtils;
import com.tuya.smart.android.common.utils.StringUtils;
import com.tuya.smart.android.device.bean.SchemaBean;
import com.tuya.smart.home.sdk.TuyaHomeSdk;
import com.tuya.smart.sdk.api.IDevListener;
import com.tuya.smart.sdk.bean.DeviceBean;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: YY
 * @Time: 2021/9/17
 * @Describe 智能设备 - 手环数据
 */
@Route(path = RoutePath.SMART_DEVICE_DATA)
public class SmartDeviceDataFragment extends MyFragment<FragDeviceDataBinding, ContainerActivity>
    implements TitleBarAction, IDevListener, Chronometer.OnChronometerTickListener {

    @Autowired(name = IntentKey.DATA)
    String name = "";

    @Autowired(name = IntentKey.ID)
    String devId = "";

    private int sportTime;

    private int reportTime;

    private String calorieStr;


    @Override
    protected DataBindingConfig getDataBindingConfig() {
        return new DataBindingConfig(R.layout.frag_device_data);
    }

    @Override
    protected void initView() {
        // 设置状态栏字体颜色
        ImmersionBar.with(this).statusBarDarkFont(true)
                .fitsSystemWindows(true).init();
        getBinding().title.setOnTitleBarListener(this);
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void initData() {
        startTimer();

        getBinding().title.setTitle(name);
        LogUtils.d("initData: "+devId);

        TuyaHomeSdk.newDeviceInstance(devId).registerDevListener(this);

        Map<String, Object> map = TuyaHomeSdk.getDataInstance().getDps(devId);
        DeviceBean deviceBean = TuyaHomeSdk.getDataInstance().getDeviceBean(devId);

        if (map != null) {
            LogUtils.d("initData "+map.toString());
            calorieStr = map.get("14").toString();
            // 卡路里
            getBinding().textView9.setText(map.get("14").toString());
            // 里程
            getBinding().tvMileage.setText(map.get("15").toString());
            // 步数
            getBinding().textView6.setText(map.get("16").toString());
            // 心率
            getBinding().tvCalorie.setText(map.get("25").toString());

            int temp = (int) map.get("104");
            LogUtils.d("initData "+temp);
            DecimalFormat df=new DecimalFormat("0.0");//设置保留位数
            // 体温
            getBinding().tvTemperature.setText( df.format((float)temp/10));
        }

        Map<String, SchemaBean> map1 = TuyaHomeSdk.getDataInstance().getSchema(devId);
        if (map1 != null) {
            Collection<SchemaBean> schemaBeans = map1.values();
            for (SchemaBean bean : schemaBeans) {
                Object value = deviceBean.getDps().get(bean.getId());
                LogUtils.d("initData "+value);
            }
        }

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        stopTimer();
    }

    @Nullable
    @Override
    public TitleBar getTitleBar() {
        return getBinding().title;
    }

    @Override
    public void onLeftClick(View v) {
        stopTimer();
        new XPopup.Builder(getMyActivity()).asConfirm(
                "提示", "是否上报运动数据？", new OnConfirmListener() {
                    @Override
                    public void onConfirm() {
                        reportData();
                    }
                }).show();

    }

    private void startTimer() {
        getBinding().chronometer.setBase(SystemClock.elapsedRealtime());
        int hour = (int) ((SystemClock.elapsedRealtime() - getBinding().chronometer.getBase()) / 1000 / 60);
        getBinding().chronometer.setFormat("0"+ hour+ ":%s");
        getBinding().chronometer.setOnChronometerTickListener(this);
        // 开始计时
        getBinding().chronometer.start();
    }

    private void stopTimer() {
        getBinding().chronometer.stop();
    }

    /**
     * DP 数据更新
     * @param devId 设备 ID
     */
    @SuppressLint("SetTextI18n")
    @Override
    public void onDpUpdate(String devId, String dpStr) {
        LogUtils.d("onDpUpdate: "+devId + " === " + dpStr);
        String depStr = dpStr.substring(1, dpStr.length() - 1);
        LogUtils.d("onDpUpdate "+depStr.length() + "=== "+ depStr);
        if (!depStr.contains(",")) {
            String[] ms = depStr.split(":");
            if (ms[0].contains("25")) {
                // 心率
                getBinding().tvCalorie.setText(ms[1]);
            } else if (ms[0].contains("104")) {
                // 体温
                int temp = Integer.parseInt(ms[1]);
                DecimalFormat df=new DecimalFormat("0.0");//设置保留位数
                getBinding().tvTemperature.setText(df.format((float)temp/10));
            }
        } else {
            String[] ms = depStr.split(",");
            for(String s:ms){
                LogUtils.d("onDpUpdate: s  "+s);
                String[] mss = s.split(":");
                if (mss[0].contains("14")) {
                    // 卡路里
                    getBinding().textView9.setText(mss[1]);
                    calorieStr = mss[1];
                } else if (mss[0].contains("15")) {
                    // 里程
                    getBinding().tvMileage.setText(mss[1]);
                } else if (mss[0].contains("16")) {
                    // 步数
                    getBinding().textView6.setText(mss[1]);
                }
            }
        }

    }

    /**
     * 设备移除回调
     * @param devId 设备id
     */
    @Override
    public void onRemoved(String devId) {
        LogUtils.d("onRemoved: ");
    }

    /**
     * 设备上下线回调。如果设备断电或断网，服务端将会在3分钟后回调到此方法。
     * @param devId  设备 ID
     * @param online 是否在线，在线为 true
     */
    @Override
    public void onStatusChanged(String devId, boolean online) {
        LogUtils.d("onStatusChanged: ");
    }

    /**
     * 网络状态发生变动时的回调
     * @param devId  设备 ID
     * @param status 网络状态是否可用，可用为 true
     */
    @Override
    public void onNetworkStatusChanged(String devId, boolean status) {
        LogUtils.d("onNetworkStatusChanged: ");
    }

    /**
     * 设备信息更新回调
     * @param devId  设备 ID
     */
    @Override
    public void onDevInfoUpdate(String devId) {

    }


    @Override
    public void onChronometerTick(Chronometer chronometer) {
        LogUtils.d("onChronometerTick: "+chronometer.getText().toString());
        sportTime++;
    }

    /**
     * 上报数据
     */
    private void reportData() {
        reportTime = sportTime / 60;
        if (reportTime < 1) {
            reportTime = 1;
        }
        HttpClient.Companion.getInstance().getApiService()
                .reportCourseTrain("run",0, reportTime, calorieStr)
                .compose(RxUtils.INSTANCE.compose())
                .subscribe(new ApiResponse<Void>() {

                    @Override
                    public void onFail(@Nullable Throwable e, @Nullable String errorMsg) {
                        getMyActivity().finish();
                    }

                    @Override
                    public void success(@Nullable Void data, @Nullable String msg) {
                        getMyActivity().finish();
                    }
                });
    }
}
